{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 创建滤波器，边缘检测\n",
    "\n",
    "### 导入资源并显示图像"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import matplotlib.image as mpimg\n",
    "\n",
    "import cv2\n",
    "import numpy as np\n",
    "\n",
    "%matplotlib inline\n",
    "\n",
    "# Read in the image\n",
    "image = mpimg.imread('images/curved_lane.jpg')\n",
    "\n",
    "plt.imshow(image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 将原图像转换为灰度图"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Convert to grayscale for filtering\n",
    "gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n",
    "\n",
    "plt.imshow(gray, cmap='gray')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### TODO: 创建一个自定义内核\n",
    "\n",
    "下面给出了一种常见的边缘检测滤波器：索贝尔算子。\n",
    "\n",
    "索贝尔滤波器常用于边缘检测以及在图像中查找强度图谱。将索贝尔滤波器应用于图像是分别在x或y方向上 **对图像的导数进行（近似）处理**的一种方式。该算子看起来如下所示。\n",
    "\n",
    "<img src=\"images/sobel_ops.png\" width=200 height=200>\n",
    "\n",
    "**你可以创建一个索贝尔 x运算子并将其应用于给定的图像。**\n",
    "\n",
    "如果想挑战自己，你可以看看是否能够通过一系列滤波器来放置图像：首先使一张图像模糊化（需要平均像素），然后检测其边缘。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create a custom kernel\n",
    "\n",
    "# 3x3 array for edge detection\n",
    "sobel_y = np.array([[ -1, -2, -1], \n",
    "                   [ 0, 0, 0], \n",
    "                   [ 1, 2, 1]])\n",
    "\n",
    "## TODO: Create and apply a Sobel x operator\n",
    "\n",
    "\n",
    "# Filter the image using filter2D, which has inputs: (grayscale image, bit-depth, kernel)  \n",
    "filtered_image = cv2.filter2D(gray, -1, sobel_y)\n",
    "\n",
    "plt.imshow(filtered_image, cmap='gray')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 测试其他滤波器！\n",
    "\n",
    "我们鼓励你创建其他类型的滤波器并应用它们，观察会发生什么情况！作为**可选练习**, 请尝试以下操作：\n",
    "* 创建一个具有十进制值权重的滤波器。\n",
    "* 创建一个5x5滤波器。\n",
    "* 将你的滤波器应用到`images`目录中的其他图像。"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
